# coding=utf-8
import datetime

from rest_framework import serializers

from utils import pretty
from .models import User, WorkerUser, BossUser


class UserLoginSer(serializers.Serializer):
    """"登录序列化"""
    username = serializers.CharField(max_length=20)
    password = serializers.CharField(max_length=20)


class ChangePasswordSer(serializers.Serializer):
    """"修改密码序列化"""
    old_password = serializers.CharField(max_length=20)
    new_password = serializers.CharField(max_length=20)


class UserDetailSer(serializers.ModelSerializer):
    """"用户详情页序列化"""
    # boss 或 worker 不同的字段
    extra_info = serializers.SerializerMethodField()
    pretty_created_time = serializers.SerializerMethodField()

    def get_pretty_created_time(self, obj):
        return pretty.date(datetime.datetime.fromtimestamp(obj.created_time))

    class Meta:
        model = User
        fields = (
            'username', 'usertype', 'phone_number', 'gender', 'zsxm', 'sfzh', 'zccs', 'avatar', 'date_joined',
            'pretty_created_time', 'extra_info')

    def get_extra_info(self, obj):
        if obj.usertype == 'boss':
            return BossSer(obj.bossuser).data
        elif obj.usertype == 'worker':
            return WorkerSer(obj.workeruser).data


class UserUpdataSer(serializers.ModelSerializer):
    """"用户信息更新序列化"""

    class Meta:
        model = User
        fields = '__all__'

    def update(self, instance, validated_data):
        """"分用户种类,覆盖update"""
        if instance.usertype == 'boss':
            data = validated_data.get('extra_info')
            ser = BossSer(instance.bossuser, data=data, partial=True)
            if ser.is_valid():
                ser.save()
            super(UserUpdataSer, self).update(instance, validated_data)
            return instance
        elif instance.usertype == 'worker':
            data = validated_data.get('extra_info')
            ser = WorkerSer(instance.workeruser, data=data, partial=True)
            if ser.is_valid():
                ser.save()
            super(UserUpdataSer, self).update(instance, validated_data)
            return instance
        else:
            super(UserUpdataSer, self).update(instance, validated_data)
            return instance


class UserSer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('zsxm', 'gender', 'avatar', 'usertype', 'sfzh')


class BossSer(serializers.ModelSerializer):
    class Meta:
        model = BossUser
        fields = '__all__'


class WorkerSer(serializers.ModelSerializer):
    class Meta:
        model = WorkerUser
        fields = '__all__'
